'''
Ethernet learning switch in Python.

Note that this file currently has the code to implement a "hub"
in it, not a learning switch.  (I.e., it's currently a switch
that doesn't learn.)
'''
from switchyard.lib.userlib import *

def main(net):
    my_interfaces = net.interfaces() 
    mymacs = [intf.ethaddr for intf in my_interfaces] #自己接口对应的mac
    #TODO: 记录mac和接口关系的表
    table_mac = {}  #记录src的mac号与对应接口关系的dict

    while True:
        try:
            timestamp,input_port,packet = net.recv_packet()
        except NoPackets:
            continue
        except Shutdown:
            return

        log_debug ("In {} received packet {} on {}".format(net.name, packet, input_port))
        #TODO: add new info to table
        table_mac[packet[0].src] = input_port
       
        if packet[0].dst in mymacs:
            log_debug ("Packet intended for me")
        else:
            #TODO: know the output port for the dst
            if packet[0].dst in table_mac and packet[0].dst != "ff:ff:ff:ff:ff:ff":
                log_debug("Sending packet {} to {}".format(packet,table_mac[packet[0].dst]))
                #now you find the intf of the mac
                net.send_packet(table_mac[packet[0].dst], packet)
            #TODO: don't now the outputport, so flood
            else:
                for intf in my_interfaces:
                  if input_port != intf.name:
                     log_debug ("Flooding packet {} to {}".format(packet, intf.name))
                     net.send_packet(intf.name, packet)

    net.shutdown()
